package com.tool.testffmpeg;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.lib.audioDecoder.AudioCodec;
import com.lib.audioDecoder.player.AUDIO_CODEC_TYPE;
import com.lib.audioDecoder.player.AudioPlayer;
import com.lib.audioDecoder.player.PCMPlayer;

import java.io.FileInputStream;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

    private final AudioPlayer mAudioPlayer =
            new AudioPlayer(AUDIO_CODEC_TYPE.AUDIO_CODEC_TYPE_726,
                    2048,8000,32000,1);
    private boolean isFLAG = false;//是否播放的标志位

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}
                    , 1);
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                isFLAG = true;

                InputStream in = null;
                try {
                    in = new FileInputStream("/sdcard/test.mp3");
                    byte[] buf = new byte[512];

                    System.out.println("开始播放");
                    int len;
                    while ((len = in.read(buf)) > 0&&isFLAG) {
                        mAudioPlayer.play(buf,0,len);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if (in != null){
                        try {
                            in.close();
                        }catch (Exception ignored){}
                    }

                    closeAudio();
                }

            }
        }).start();
    }

    private void closeAudio(){
        System.out.println("音频结束播放");
        isFLAG = false;
        mAudioPlayer.close();
    }

    @Override
    protected void onStop() {
        super.onStop();
        closeAudio();
    }
}